<?php

namespace app\index\controller;

use library\Controller;
use app\common\service\CompressService;
use app\admin\service\MemberService;
use library\File;
use think\Db;

/**
 * 应用入口
 * Class Index
 * @package app\index\controller
 */
class Index extends Base
{
    /**
     * 首页
     */
    public function index()
    {
    	$this->company_name = $this->company['name'];
		$this->point = $this->company['point'];	
		$contract = Db::name('system_contract')->where(['company_id'=>$this->company['id']])->order('id desc')->field('id,status,start_date,end_date,setmeal_type,people,account_type')->find();
//		if(!$contract){			
//			$this->fetch('noindex');    
//		}
		$this->start_date = $contract['start_date'];
		$this->end_date = $contract['end_date'];
		$this->status = $contract['status'];
		$this->people = $contract['people'];
		//公司类型
		$member = Db::name('system_member')->where(['id'=>$this->company['mid']])->find();
		$this->account_type = $member['account_type'];
		if($member['account_type'] == 2){
			$this->master_name = Db::name('system_company')->where(['id'=>$member['master']])->value('name');
		}
		//查看有没有待付款的社保账单
		$this->insbill = Db::name('system_insbill')->where(['company_id'=>$this->company['id'],'status'=>2,'is_deleted'=>0])->count();
		//查看有没有待付款的增值账单
		$this->cadditional_bill = Db::name('system_cadditional_bill')->where(['company_id'=>$this->company['id'],'status'=>2,'is_deleted'=>0])->count();
		//在职人数
		$this->in_bao = Db::name('system_company_person')->where(['company_id'=>$this->company['id'],'status'=>1])->count();
		//养老人数
		$this->ylnum = Db::name('system_insurance_result')->where(['company_id'=>$this->company['id'],'contract_id'=>$contract['id'],'status'=>1,'insurance'=>1])->count();
		//工伤人数
		$this->gsnum = Db::name('system_insurance_result')->where(['company_id'=>$this->company['id'],'contract_id'=>$contract['id'],'status'=>1,'insurance'=>2])->count();
		//失业人数
		$this->synum = Db::name('system_insurance_result')->where(['company_id'=>$this->company['id'],'contract_id'=>$contract['id'],'status'=>1,'insurance'=>3])->count();
		//医疗人数
		$this->yilnum = Db::name('system_insurance_result')->where(['company_id'=>$this->company['id'],'contract_id'=>$contract['id'],'status'=>1,'insurance'=>4])->count();
		//公积金人数
		$this->gjjnum = Db::name('system_insurance_result')->where(['company_id'=>$this->company['id'],'contract_id'=>$contract['id'],'status'=>1,'insurance'=>5])->count();
		//托管档案人数
		//$inbaoids = Db::name('system_company_person')->where(['company_id'=>$this->company['id'],'status'=>1])->column('person_id');
		$this->archives = Db::name('system_archives')->where(['company_id'=>$this->company['id'],'status'=>2,'person_status'=>1])->count();
		//社保服务公司办理数量
		$this->csocsecs = Db::name('system_service_handle')->where(['type'=>1,'status'=>[1,2,3],'company_id'=>$this->company['id'],'is_deleted'=>0])->count();
		//社保服务员工办理数量
		$this->psocsecs = Db::name('system_service_handle')->where(['type'=>2,'status'=>[1,2,3],'company_id'=>$this->company['id'],'is_deleted'=>0])->count();
		
		if($this->csocsecs == 0 && $this->psocsecs == 0){
			//社保服务公司办理百分比
			$this->csocsecs_per = 0;
			//社保服务公司办理百分比
			$this->psocsecs_per = 0;
		}else{
			//社保服务公司办理百分比
			$this->csocsecs_per = percent([$this->csocsecs,$this->psocsecs])[0];
			//社保服务公司办理百分比
			$this->psocsecs_per = percent([$this->csocsecs,$this->psocsecs])[1];
		}		
		//社保服务公司办理中数量
		$this->csocsecs_soon = Db::name('system_service_handle')->where(['type'=>1,'status'=>[1,2],'company_id'=>$this->company['id'],'is_deleted'=>0])->count();
		//社保服务公司已办理数量
		$this->csocsecs_end = Db::name('system_service_handle')->where(['type'=>1,'status'=>3,'company_id'=>$this->company['id'],'is_deleted'=>0])->count();
		//社保服务员工办理中数量
		$this->psocsecs_soon = Db::name('system_service_handle')->where(['type'=>2,'status'=>[1,2],'company_id'=>$this->company['id'],'is_deleted'=>0])->count();
		//社保服务员工已办理数量
		$this->psocsecs_end = Db::name('system_service_handle')->where(['type'=>2,'status'=>3,'company_id'=>$this->company['id'],'is_deleted'=>0])->count();
		//增员办理中
		$this->increase_soon = Db::name('system_increase')->where(['company_id'=>$this->company['id'],'is_deleted'=>0,'status'=>1])->count();
		//增员未通过
		$this->increase_end = Db::name('system_increase')->where(['company_id'=>$this->company['id'],'is_deleted'=>0,'status'=>3])->count();
		//减员办理中
		$this->downsizing_soon = Db::name('system_downsizing')->where(['company_id'=>$this->company['id'],'is_deleted'=>0,'status'=>1])->count();
		//减员未通过
		$this->downsizing_end = Db::name('system_downsizing')->where(['company_id'=>$this->company['id'],'is_deleted'=>0,'status'=>3])->count();
		$year = date("Y",time());
		$first = $year."-01-01";
		$end = date("Y-m-d",time());
		$months = splitMonths($first,$end);
		//客服信息
		$this->csr = Db::name('system_user')->where(['id'=>$this->company['csr_id']])->field('nickname,qq,phone')->find();
		if($contract['setmeal_type'] == 2 || !$contract){		 
			foreach($months as $k=>$v){
				$increase[] = Db::name('system_increase')->where(['company_id'=>$this->company['id'],'contract_id'=>$contract['id'],'status'=>2,'is_deleted'=>0])->whereBetweenTime('create_at', $v[0], date('Y-m-d',(strtotime($v[1])+86400)))->count();
				$downsizing[] = Db::name('system_downsizing')->where(['company_id'=>$this->company['id'],'contract_id'=>$contract['id'],'status'=>2,'is_deleted'=>0])->whereBetweenTime('create_at', $v[0], date('Y-m-d',(strtotime($v[1])+86400)))->count();
			}
			$this->increase = $increase;
			$this->downsizing = $downsizing;	
			//判断是否提醒续约
			if($contract['end_date'] && $contract['status'] == 1){
				$today = date('Y-m-d',time());
		    	$month = after_month($today,1);
		        $lastday = get_lastday($month);
		        $end_date = $month.'-'.$lastday;
		        $end_date = strtotime($end_date);
		        if(strtotime($contract['end_date']) <= $end_date){
		        	$this->reminder = 1;
		        }
			}		
			$this->fetch('newindex');    
		}else{
			foreach($months as $k=>$v){
				$consumption[] = Db::name('system_point_detailed')->where(['mid'=>$this->company['mid'],'type'=>[2,4]])->whereBetweenTime('create_at', $v[0], date('Y-m-d',(strtotime($v[1])+86400)))->sum('point');
				$refund[] = Db::name('system_point_detailed')->where(['mid'=>$this->company['mid'],'type'=>3])->whereBetweenTime('create_at', $v[0], date('Y-m-d',(strtotime($v[1])+86400)))->sum('point');
			}
			$this->consumption = $consumption;
			$this->refund = $refund;
			$service = new Service();
			$this->service = $service->index();
			//判断是否提醒续约
			if($contract['account_type'] == 1 && $this->company['point'] <= 5 && $contract['status'] == 1){
				$this->reminder = 1;
			}
	    	$this->fetch();       
		}
		   
    }
    
    
    /**
     * 首页弹窗接口
     */
    public function person_list()
    {
    	$data = $this->request->post();
    	if(!in_array($data['type'],[1,2,3,4,5,6])){
    		$this->error('参数错误');
    	}
    	$contract_id = Db::name('system_contract')->where(['company_id'=>$this->company['id']])->order('id desc')->value('id');
    	$list = [];
    	switch($data['type']){
    		case '1':
	    		//养老保险员工
	    		$persons = Db::name('system_insurance_result')->where(['company_id'=>$this->company['id'],'contract_id'=>$contract_id,'status'=>1,'insurance'=>1])->column('person_id');
	    		if($persons){
	    			$list = Db::name('system_person')->where(['id'=>$persons])->field('name,id_number')->select();
	    		}
	    		break;
	    	case '2':
	    		//工伤保险员工
	    		$persons = Db::name('system_insurance_result')->where(['company_id'=>$this->company['id'],'contract_id'=>$contract_id,'status'=>1,'insurance'=>2])->column('person_id');
	    		if($persons){
	    			$list = Db::name('system_person')->where(['id'=>$persons])->field('name,id_number')->select();
	    		}
	    		break;
	    	case '3':
	    		//失业保险员工
	    		$persons = Db::name('system_insurance_result')->where(['company_id'=>$this->company['id'],'contract_id'=>$contract_id,'status'=>1,'insurance'=>3])->column('person_id');
	    		if($persons){
	    			$list = Db::name('system_person')->where(['id'=>$persons])->field('name,id_number')->select();
	    		}
	    		break;
	    	case '4':
	    		//医疗保险员工
	    		$persons = Db::name('system_insurance_result')->where(['company_id'=>$this->company['id'],'contract_id'=>$contract_id,'status'=>1,'insurance'=>4])->column('person_id');
	    		if($persons){
	    			$list = Db::name('system_person')->where(['id'=>$persons])->field('name,id_number')->select();
	    		}
	    		break;
	    	case '5':
	    		//公积金员工
	    		$persons = Db::name('system_insurance_result')->where(['company_id'=>$this->company['id'],'contract_id'=>$contract_id,'status'=>1,'insurance'=>5])->column('person_id');
	    		if($persons){
	    			$list = Db::name('system_person')->where(['id'=>$persons])->field('name,id_number')->select();
	    		}
	    		break;
	    	case '6':
	    		//档案托管员工
	    		$list = Db::name('system_archives')->where(['company_id'=>$this->company['id'],'status'=>2,'person_status'=>1])->field('name,id_number')->select();
	    		break;
    	}
    	$this->success('获取成功', $list);
    }
    


	/**
     * 套餐详情
     */
    public function package()
    {
    	$type = $this->company['setmeal_type'];
    	$list = Db::name('system_package')->where(['is_deleted'=>0,'type'=>$type,'status'=>1,'show'=>1])->select();
    	foreach($list as $k=>$v){
    		$yu = $v['month'] % 12;
    		if($yu == 0){
    			$list[$k]['service_time'] = ($v['month'] / 12).'年';
    		}else{
    			$list[$k]['service_time'] = $v['month'].'个月';
    		}
    	} 
    	$this->list = $list;
    	$this->type = $type;
    	$this->fetch();
    }
    
    
    /**
     * 套餐详细信息
     */
    public function details()
    {
    	if($this->request->isPost()){
    		$data = $this->request->post();
    		if(empty($data['id']) || !$data['id']){
				$this->error('参数错误');
			}
			$package = Db::name('system_package')->where(['is_deleted'=>0,'show'=>1,'id'=>$data['id']])->find();
			if(!$package){
	    		$this->error('套餐错误，无法下单');
	    	}
	    	//生成订单
	    	$arr = [
	    		'code' => $this->company['unique'].'3'.mt_rand (10000,99999),
	    		'company_id' => $this->company['id'],
	    		'package_id' => $data['id'],
	    		'setmeal_type' => $package['type'],
	    		'type' => 1,
	    		'status' => 1,
	    		'receivable' => $package['price'],
	    		'balance' => (float)sprintf("%.2f",0 - $package['price'])
	    	];
	    	$re = Db::name('system_package_order')->insertGetId($arr);
	    	if($re){
	    		$ins = [
	        		'code' => $arr['code'],
	        		'jump_id' => $re,
	        		'company_id' => $this->company['id'],
	        		'bill_type' => 2,
	        		'cost_type' => 2,
	        		'receivable' => $arr['receivable'],
	        		'balance' => $arr['balance']
	        	];
	        	Db::name('system_financial_bill')->insert($ins);
	        	$this->success('订单创建成功', ['id'=>$re]);
	    	}
    	}else{
    		$id = $this->request->get('id');
	    	$package = Db::name('system_package')->where(['is_deleted'=>0,'show'=>1,'id'=>$id])->find();
	    	if(!$package){
	    		$this->redirect('index/publicot/transition', ['info'=>'暂无该套餐','type'=>'7']);
	    	}
	    	$yu = $package['month'] % 12;
    		if($yu == 0){
    			$package['service_time'] = ($package['month'] / 12).'年';
    		}else{
    			$package['service_time'] = $package['month'].'个月';
    		}
	    	$this->package = $package;
	    	$this->fetch();
    	}
    	
    }
    
    /**
     * 判断能否续约
     */
    private function is_renewal()
    {
    	$contract = Db::name('system_contract')->where(['company_id'=>$this->company['id'],'status'=>1])->find();
    	if(!$contract){
    		return false;
    	}
    	if($contract['setmeal_type'] == 1 && $contract['account_type'] == 2){
    		return false;
    	}
    	return true;
//  	$after_month = after_month($contract['end_date'],1);
//  	$before_month = before_month($contract['end_date'],1);
//  	$start_time = strtotime($before_month);
//  	$end_time = strtotime($after_month);
//  	if((time() < $start_time) || (time() >= $end_time)){
//  		return false;
//  	}else{
//  		return true;
//  	}  
    }
    
    /**
     * 判断能否续约
     */
    public function renewal_check()
    {  
    	$re = $this->is_renewal();
    	if(!$re){
    		$this->error('无法续约');
    	}else{
    		$this->success('可以续约');
    	}
    }
    
    
    /**
     * 续约套餐
     */
    public function renewal_package()
    {
    	$contract = Db::name('system_contract')->where(['company_id'=>$this->company['id'],'status'=>1])->order('id desc')->find();
    	if(!$contract){
    		$this->redirect('index/publicot/transition', ['info'=>'暂时无法续约','type'=>'9']);
    	}  	
    	if($contract['setmeal_type'] == 1 && $contract['account_type'] == 2){
    		$this->redirect('index/publicot/transition', ['info'=>'暂时无法续约','type'=>'9']);
    	}
    	$list = Db::name('system_package')->where(['is_deleted'=>0,'type'=>$contract['setmeal_type'],'status'=>1,'show'=>1])->select();
    	foreach($list as $k=>$v){
    		$yu = $v['month'] % 12;
    		if($yu == 0){
    			$list[$k]['service_time'] = ($v['month'] / 12).'年';
    		}else{
    			$list[$k]['service_time'] = $v['month'].'个月';
    		}
    	}   	
    	$this->list = $list;
    	$this->type = $contract['setmeal_type'];
    	$this->fetch();
    }
    
    
    /**
     * 续约套餐详细信息
     */
    public function renewal_details()
    {
    	if($this->request->isPost()){
    		$data = $this->request->post();
    		if(empty($data['id']) || !$data['id']){
				$this->error('参数错误');
			}
			$res = $this->is_renewal();
	    	if(!$res){
	    		$this->error('无法续约');
	    	}
			$package = Db::name('system_package')->where(['is_deleted'=>0,'show'=>1,'id'=>$data['id']])->find();
			if(!$package){
	    		$this->error('套餐错误，无法下单');
	    	}
	    	//生成订单
	    	$arr = [
	    		'code' => $this->company['unique'].'4'.mt_rand (10000,99999),
	    		'company_id' => $this->company['id'],
	    		'package_id' => $data['id'],
	    		'setmeal_type' => $package['type'],
	    		'type' => 2,
	    		'status' => 1,
	    		'receivable' => $package['price'],
	    		'balance' => (float)sprintf("%.2f",0 - $package['price'])
	    	];
	    	$re = Db::name('system_package_order')->insertGetId($arr);
	    	if($re){
	    		$ins = [
	        		'code' => $arr['code'],
	        		'jump_id' => $re,
	        		'company_id' => $this->company['id'],
	        		'bill_type' => 2,
	        		'cost_type' => 2,
	        		'receivable' => $arr['receivable'],
	        		'balance' => $arr['balance']
	        	];
	        	Db::name('system_financial_bill')->insert($ins);
	        	$this->success('订单创建成功', ['id'=>$re]);
	    	}
    	}else{
    		$re = $this->is_renewal();
	    	if(!$re){
	    		$this->redirect('index/publicot/transition', ['info'=>'暂时无法续约','type'=>'9']);
	    	}
    		$id = $this->request->get('id');
	    	$package = Db::name('system_package')->where(['is_deleted'=>0,'show'=>1,'id'=>$id])->find();
	    	if(!$package){
	    		$this->redirect('index/publicot/transition', ['info'=>'暂无该套餐','type'=>'7']);
	    	}
	    	$yu = $package['month'] % 12;
    		if($yu == 0){
    			$package['service_time'] = ($package['month'] / 12).'年';
    		}else{
    			$package['service_time'] = $package['month'].'个月';
    		}
	    	$this->package = $package;
	    	$this->fetch();
    	}
    	
    }
    
    
    
    /**
     * 公司信息展示
     */
    public function info()
    {
    	$member = Db::name('system_member')->where(['id'=>$this->company['mid']])->find();
    	if($this->company['status'] == 1){
    		//未审核
    		if($this->request->isPost()){
    			$data = $this->request->post();
    			$verification = $this->_input([
	                'name' => trim($this->request->post('name')),
	            ], [
	                'name' => 'require|min:6',
	            ], [
	                'name.min' => '公司名称长度不能少于6位有效字符！',
	            ]);
				if(!$data['business_license']){
	        		$this->error('请上传营业执照');
	        	}
	        	$where = [['name', 'eq', $data['name']],['id ', 'neq', $this->company['id']]];
            	if (Db::name('system_company')->where($where)->count() > 0) {
	                $this->error('公司已存在，请更改公司名称');
	            }
	            Db::name('system_company')->where(['id'=>$this->company['id']])->update($data);
	            MemberService::member_edit($this->company['mid'],['loginname'=>$data['name']]);
	            $this->success('修改成功！');
    		}else{
    			$this->taxid = get_option('taxid');
        		$this->invoice = get_option('invoice');
    			$this->mobile = $member['mobile'];
    			$this->fetch('perfect');
    		}    		
    	}else{
    		$this->business_license = $this->company['business_license'] ? 'http://'.$_SERVER['SERVER_NAME'].$this->company['business_license'] : '';
    		
    		$this->taxid = get_option('taxid')[$this->company['taxid']];
    		$this->invoice = get_option('invoice')[$this->company['invoice']];
			$this->mobile = $member['mobile'];
    		//已审核
    		$this->fetch('info');
    	}
    }
    
    
    /**
     * 更改手机号
     */
    public function change_mobile()
    {
    	$data = $this->request->post();
    	trim_array($data);
        $verify = Db::name('system_verify')->where(['mobile'=>$data['mobile'],'type'=>4,'status'=>0])->order('id desc')->limit(1)->find();
        if(!$verify || $verify['code'] != $data['verify']){
        	$this->error('验证码错误');       	
        }
        if(time() - $verify['create_at'] > 900){
        	$this->error('验证码已失效');       	
        }
        
        //检查手机号是否被注册
        $find = Db::name('system_member')->where(['mobile'=>$data['mobile'],'type'=>1])->find();
        if($find){
        	if($find['id'] == $this->company['mid']){
        		$this->error('请更换新手机号');    
        	}else{
        		$this->error('手机号已被注册');
        	}       	
        }
    	Db::name('system_member')->where(['id'=>$this->company['mid'],'type'=>1])->update(['mobile'=>$data['mobile']]);
    	Db::name('system_verify')->where(['id'=>$verify['id']])->update(['status'=>1]);
    	$this->success('修改成功！',['mobile'=>$data['mobile']]);
    }
    
    
    
    /**
     * 营业执照上传
     */  
	public function upload()
	{
	    // 获取表单上传文件 例如上传了001.jpg
	    $file = request()->file('image');
		if (empty($file) || !$file) {
            $this->error('文件上传异常，文件可能过大或未上传');
       	} 
        if (!$file->checkExt('jpg,png,jpeg')) {
            return json(['uploaded' => false, 'error' => ['message' => '文件上传类型错误']]);
        }
        if ($file->checkExt('php,sh')) {
            return json(['uploaded' => false, 'error' => ['message' => '可执行文件禁止上传']]);
        }
        if (!$file->checkSize(10485760)) {
            return json(['uploaded' => false, 'error' => ['message' => '文件过大']]);
        }		
		$path = 'upload/';
        if(!file_exists($path)){
            mkdir($path,0777,true);
        }
		$realName = $file->getInfo()['name'];
	    $info = $file->move($path);
	    if($info){
	    	$business_license = '/'.$path.$info->getSaveName();
	        $url = 'http://'.$_SERVER['SERVER_NAME'].$business_license;
			$this->success('上传成功',['business_license'=>$business_license,'url'=>$url]);
	    }else{
	        // 上传失败获取错误信息
	        $this->error($file->getError());
	    }
	}
	
	
	/**
     * 增值服务列表
     */
    public function services()
    {
    	$list = Db::name('system_service')->where(['type'=>2,'is_deleted' =>'0','status'=>1])->select();
		if($list){
			foreach($list as $k=>$v){
				$list[$k]['class'] = $v['class'] ? get_option('service_class_increment')[$v['class']] : '';
				$list[$k]['target'] = $v['target'] == 1 ? '公司' : '员工';
			}
		}
		$this ->list = $list;
		$contract = Db::name('system_contract')->where(['company_id'=>$this->company['id'],'status'=>1])->order('id desc')->field('id,status,end_date,setmeal_type,people')->find();
		if($contract){
			$this ->setmeal_type = $contract['setmeal_type']; 
		}else{
			$this ->setmeal_type = $this->company['setmeal_type']; 
		}
    		
        $this->fetch();  
    }
    
    
    /**
     * 使用说明
     */
    public function instructions()
    {
    	$agreement =  Db::name('system_agreement')->where(['id' => 3,'is_deleted'=>0])->find();
    	$this->agreement = $agreement;
    	$this->fetch();
    }
    
    
}
